package jjn.round2;

import commons.LinkedListHelper;
import commons.ListNode;

import java.util.List;

/**
 * @author Jjn
 * @since 2023/7/3 13:38
 */
public class LeetCode445 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head1 = reverseListNode(l1);
        ListNode head2 = reverseListNode(l2);
        ListNode start1 = head1;
        ListNode start2 = head2;
        int carry = 0;
        ListNode dummy = new ListNode();
        ListNode start = dummy;
        while (start1 != null || start2 != null) {
            int val1 = (start1 == null) ? 0 : start1.val;
            int val2 = (start2 == null) ? 0 : start2.val;
            int sum = val1 + val2 + carry;
            carry = sum / 10;
            int rest = sum % 10;
            start.next = new ListNode(rest);
            start = start.next;
            if (start1 != null) {
                start1 = start1.next;
            }
            if (start2 != null) {
                start2 = start2.next;
            }
        }
        if (carry > 0) {
            start.next = new ListNode(carry);
        }
        return reverseListNode(dummy.next);
    }
    
    private ListNode reverseListNode(ListNode node) {
        ListNode head = node, pre = null;
        while (head != null) {
            ListNode temp = head.next;
            head.next = pre;
            pre = head;
            head = temp;
        }
        return pre;
    }
    
    public static void main(String[] args) {
        ListNode l1 = LinkedListHelper.buildLinkedList(List.of(7, 2, 4, 3));
        ListNode l2 = LinkedListHelper.buildLinkedList(List.of(5, 6, 4));
        ListNode listNode = new LeetCode445().addTwoNumbers(l1, l2);
        while (listNode != null) {
            System.out.println("listNode.val = " + listNode.val);
            listNode = listNode.next;
        }
    }
}
